import base64
import json
import pickle

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU


class CartsView(View):
    def get(self, request):
        # 获取购物车页面, 1,登录用户购物车, 2, 非登录用户
        # 1, 接收数据
        user = request.user

        # 2, 校验数据

        # 3, 处理业务
        if user.is_authenticated:
            # 登录用户

            # 先判断cookie中有没有购物车
            cart_bytes = request.COOKIES.get('carts')
            if cart_bytes:
                cart_dict = pickle.loads(base64.b64decode(cart_bytes))
                # 有, 覆盖到redis中
                """
                {
                    'sku_id':{
                        'count':2,
                        'selected':True
                    }
                }"""
                redis_client = get_redis_connection('carts')
                """
                'cart_user_id': {'sku_id':count}
                'selected_user_id':{sku_id}
                """

                for sku_id, count_selected in cart_dict.items():
                    redis_client.hset('cart_%s'%user.id, sku_id, count_selected['count'])
                    if count_selected['selected']:  # 是bool值
                        redis_client.sadd('selected_%s'%user.id, sku_id)
                    else:
                        redis_client.srem('selected_%s'%user.id, sku_id)

            # 没有, 不用操作

            # 数据从redis中获取, 合并后内容
            # 创建redis客户端
            redis_client = get_redis_connection('carts')
            # 获取数据, hash,  set
            cart_redis = redis_client.hgetall('cart_%s' % user.id)
            # 结构
            selected_redis = redis_client.smembers('selected_%s' % user.id)

            # 构造成前端需要的数据结构
            sku_list = []

            for sku_id, count in cart_redis.items():
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id': sku.id,
                    'name': sku.name,
                    'price': float(sku.price),
                    'count': int(count),
                    'default_image_url': sku.default_image_url.url,
                    'amount': float(sku.price * int(count)),
                    'selected': str(sku_id in selected_redis)
                }
                sku_list.append(sku_data)

            context = {
                'cart_skus': sku_list
            }
            # 删除cookie操作
            response = render(request, 'cart.html', context=context)
            response.delete_cookie('carts')
            return response
            #
        else:
            # 非登录用户
            # 从cookie中获取购物车
            cart_b64 = request.COOKIES.get('carts')

            if cart_b64:
                # base64 -> bytes
                cart_bytes = base64.b64decode(cart_b64)

                # bytes -> dict  # cart_dict
                cart_dict = pickle.loads(cart_bytes)
            else:
                cart_dict = {}
            # cart_dict = {
            #     'sku_id':{
            #         'count':1,
            #         'selected':True
            #     }
            # }

            # 遍历购物车, 构造购物车数据
            sku_list = []
            for sku_id in cart_dict:
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id': sku.id,
                    'name': sku.name,
                    'price': float(sku.price),
                    'count': int(cart_dict[sku_id]['count']),
                    'default_image_url': sku.default_image_url.url,
                    'amount': float(sku.price * int(cart_dict[sku_id]['count'])),
                    'selected': str(cart_dict[sku_id]['selected'])
                }
                sku_list.append(sku_data)

            # 传给模板, vue接收数据, 渲染页面
            context = {
                'cart_skus': sku_list
            }
            # 4, 返回响应
            return render(request, 'cart.html', context=context)

    def post(self, request):
        # 添加购物车
        # 1, 接收数据
        # {"sku_id":16,"count":1}
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')

        # 2, 校验数据
        if not all([sku_id, count]):
            return JsonResponse({'code': 9999, 'errmsg': '参数不全'})

        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '商品id不正确'})

        if int(count) < 1:
            return JsonResponse({'code': 9999, 'errmsg': '商品数量不正确'})

        # 3, 处理业务
        user = request.user
        if user.is_authenticated:
            # 登录用户加入购物车数据
            # 把用户的数据  存入redis  cart_1:{'sku_id':count}
            # 获取redis客户端
            redis_client = get_redis_connection('carts')

            # 商品id和数量count 存入 hash,  key: cart_user_id
            # redis_client.hset('cart_%s' % user.id, sku_id, count)
            # 添加购物车数量应该累加
            redis_client.hincrby('cart_%s' % user.id, sku_id, count)

            # 商品的选择状态 存入 set , key: selected_user_id
            # 加入购物车默认就是选择状态
            redis_client.sadd('selected_%s' % user.id, sku_id)

            # 4, 返回响应
            res = {
                'code': 0,
                'errmsg': '成功',
                'sku_count': count
            }
            return JsonResponse(res)
            pass
        else:
            # 非登录用户加入购物车数据
            # 把数据加入到cookie中
            # {
            #     'sku_id':{
            #         'count':1,
            #         'selected':True
            #     }
            # }

            # 先判断原来购物车的内容, 如果添加的商品已经存在, 则需要累加数量

            # 从cookie中获取购物车
            cart_b64 = request.COOKIES.get('carts')

            if cart_b64:
                # 判断cookie中是否有购物车
                # base64 -> bytes
                cart_bytes = base64.b64decode(cart_b64)

                # bytes -> dict  # cart_dict
                cart_dict = pickle.loads(cart_bytes)
            else:
                # 如果没有, 就设置空购物车
                cart_dict = {}

            if cart_dict:
                # 判断cookie中是否有购物车
                pass
            else:
                # 如果没有, 就设置空购物车
                cart_dict = {}

            if sku_id in cart_dict:
                # 如果商品已经存在购物车内, 就累加数量
                cart_dict[sku_id]['count'] += int(count)
            else:
                # 如果商品不存在, 就设置新的内容
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': True
                }

            # 1, 把字典转成二进制
            cart_bytes = pickle.dumps(cart_dict)

            # 2, 把二级制转成base64
            cart_b64 = base64.b64encode(cart_bytes)

            # 3, 把base64保存到cookies 中
            res = {
                'code': 0,
                'errmsg': '成功',
                'sku_count': count
            }
            response = JsonResponse(res)
            response.set_cookie('carts', cart_b64, expires=3600 * 24 * 14)

            return response
            pass

        pass

    def put(self, request):
        # 根据前端传来的 sku_id, count, 和 selected 覆盖购物车内容
        # 1, 接收数据
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected')

        # 2, 校验数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '商品id不正确'})

        try:
            count = int(count)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '数量格式不正确'})

        if count < 1:
            return JsonResponse({'code': 9999, 'errmsg': '数量不正确'})

        # todo: 判断selected

        # 3, 处理业务
        user = request.user
        if user.is_authenticated:
            # 登录用户
            # redis中获取
            redis_client = get_redis_connection('carts')
            # cart_redis = redis_client.hgetall('cart_%s' % user.id)
            selected_redis = redis_client.smembers('selected_%s' % user.id)

            # 新数据覆盖到购物车中
            # 1,设置数量
            redis_client.hset('cart_%s' % user.id, sku_id, count)

            # 2,设置选择状态
            if selected:
                # 被选择了
                redis_client.sadd('selected_%s' % user.id, sku_id)
            else:
                # 取消选择了
                redis_client.srem('selected_%s' % user.id, sku_id)

            res = {
                'code': 0,
                'errmsg': '成功',
                'cart_sku': {
                    'id': sku.id,
                    'name': sku.name,
                    'price': float(sku.price),
                    'count': int(count),
                    'default_image_url': sku.default_image_url.url,
                    'amount': float(sku.price * int(count)),
                    'selected': selected
                }
            }

            return JsonResponse(res)


        else:
            # 非登录用户
            # sku_id = data.get('sku_id')
            # count = data.get('count')
            # selected = data.get('selected')
            # 1, 从cookie中获取购物车
            cart_b64 = request.COOKIES.get('carts')
            if cart_b64:
                cart_dict = pickle.loads(base64.b64decode(cart_b64))
            else:
                cart_dict = {}

            # 2, 把新的数据设置到购物车中
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 3, 再保存到cookie
            cart_b64 = base64.b64encode(pickle.dumps(cart_dict))

            res = {
                'code': 0,
                'errmsg': '成功',
                'cart_sku': {
                    'id': sku.id,
                    'name': sku.name,
                    'price': float(sku.price),
                    'count': count,
                    'selected': selected,
                    'amount': float(sku.price * count),
                    'default_image_url': sku.default_image_url.url
                }
            }

            # 4, 返回响应

            response = JsonResponse(res)
            response.set_cookie('carts', cart_b64, expires=3600 * 24 * 14)
            return response

    def delete(self, request):
        # 删除购物车
        # 1, 接收数据
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')

        # 2, 校验数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code': 9999, 'errmsg': '商品id不正确'})
        # 3, 处理业务
        user = request.user

        if user.is_authenticated:
            # 登录用户
            # redis中取数据
            redis_client = get_redis_connection('carts')

            redis_client.hdel('cart_%s' % user.id, sku_id)
            redis_client.srem('selected_%s' % user.id, sku_id)

            # 返回结果
            res = {
                'code': 0,
                'errmsg': '成功'
            }
            return JsonResponse(res)

        else:
            # 非登录用户
            # 从cookie中取数据
            cart_bytes = request.COOKIES.get('carts')
            if cart_bytes:
                cart_dict = pickle.loads(base64.b64decode(cart_bytes))
                # 删除cart_dict中的sku_id的数据
                cart_dict.pop(sku_id)
            else:
                cart_dict = {}

            # dict -> base64
            cart_base64 = base64.b64encode(pickle.dumps(cart_dict))
            # 返回数据
            res = {
                'code': 0,
                'errmsg': '成功'
            }
            response = JsonResponse(res)
            response.set_cookie('carts', cart_base64, expires=3600 * 24 * 14)

            return response


class CartsSelectionView(View):
    def put(self, request):
        # 全选/不全选购物车
        # 1, 接收数据
        data = json.loads(request.body.decode())
        selected = data.get('selected')
        # 2, 校验数据
        pass
        # 3, 处理业务
        user = request.user

        if user.is_authenticated:
            # 登录
            redis_client = get_redis_connection('carts')
            cart_redis_sku_ids = redis_client.hkeys('cart_%s'%user.id)

            # 根据选中状态, 设置  redis中的数据
            if selected:
                redis_client.sadd('selected_%s'%user.id, *cart_redis_sku_ids)
            else:
                redis_client.srem('selected_%s'%user.id, *cart_redis_sku_ids)

            res = {
                'code':0,
                'errmsg':'成功'
            }
            return JsonResponse(res)
            pass
        else:
            # 非登录
            cart_bytes = request.COOKIES.get('carts')
            if cart_bytes:
                cart_dict = pickle.loads(base64.b64decode(cart_bytes))
                # {
                #     sku_id:{
                #         'count':3,
                #         'selected':True
                #     },
                #     sku_id: {
                #         'count': 3,
                #         'selected': True
                #     }
                # }

                for sku_id, value in cart_dict.items():
                    value['selected'] = selected


            else:
                cart_dict = {}

            # dict -> base64
            # 4, 返回响应

            cart_base64 = base64.b64encode(pickle.dumps(cart_dict))

            res = {
                'code':0,
                'errmsg':'成功',
            }

            response = JsonResponse(res)
            response.set_cookie('carts', cart_base64, expires=3600*24*14)

            return response


class CartsSimpleView(View):
    def get(self, request):
        # 获取简单购物车数据

        # 1, 接收数据
        user = request.user

        # 2, 校验数据
        pass

        # 3, 处理业务
        if user.is_authenticated:
            # 登录状态
            redis_client = get_redis_connection('carts')
            # 购物车
            cart_redis = redis_client.hgetall('cart_%s'%user.id)

            # 组装数据
            sku_list = []
            """
            {
                sku_id:count
            }
            """


            for sku_id, count in cart_redis.items():
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id':sku.id,
                    'name':sku.name,
                    'count':int(count),
                    'default_image_url': sku.default_image_url.url
                }
                sku_list.append(sku_data)

            res = {
                'code':0,
                'errmsg':'成功',
                'cart_skus':sku_list
            }
            return JsonResponse(res)
            pass
        else:
            # 非登录
            # 从cookie中获取数据
            cart_bytes = request.COOKIES.get('carts')

            # 转码
            if cart_bytes:
                cart_dict = pickle.loads(base64.b64decode(cart_bytes))
            else:
                cart_dict = {}
            # 遍历购物车, 组装数据

            sku_list = []
            """
            {
                sku_id:{
                    count:1,
                    selected:True
                }
            }
            """

            for sku_id, count_selected in cart_dict.items():
                sku = SKU.objects.get(id=sku_id)
                sku_data = {
                    'id':sku.id,
                    'name':sku.name,
                    'count':count_selected['count'],
                    'default_image_url':sku.default_image_url.url,

                }
                sku_list.append(sku_data)

            # 构造res
            res = {
                'code':0,
                'errmsg':'成功',
                'cart_skus':sku_list
            }

            # 返回响应
            return JsonResponse(res)
            pass

        # 4, 返回响应

        pass
